<template>
	<div class="container">
		<div>
			<a-form ref="searchRef" :label-col="{style: { width: '120px' }}" :model="searchState" @finish="initData()">
				<a-row
					:gutter="20">
					<a-row :gutter="20">
						<a-col :span="24">
							<a-form-item label="状态">
								<a-radio-group v-model:value="searchState.status" @change="current=1;loading=true;initData()">
									<a-radio-button v-for="option of statusList" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料名称">
								<a-input v-model:value="searchState.material_name" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="浮动类型">
								<a-select v-model:value="searchState.price_type" placeholder="请选择浮动物资类型" :options="priceTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="时间">
								<a-date-picker v-if="searchState.price_type === 1" v-model:value="searchState.setting_date" format="YYYY/MM" picker="month" />
								<a-date-picker v-else v-model:value="searchState.setting_date" format="YYYY/MM/DD" />
							</a-form-item>
						</a-col>
						<a-col :span="8" class="text-center">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
									<a-button v-permission="84" type="primary" @click="addPrice()">
										<plus-outlined />添加价格记录
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-row>
			</a-form>
			<a-form ref="editRef" :model="editIndex">
				<a-table class="table" :columns="innerColumns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="formDataList" :pagination="false" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record, index }">
						<!-- 物资名称 -->
						<template v-if="column.dataIndex === 'name' && editIndex[record.key]">
							<a-form-item :name="[record.key, 'material', 'source_id']" :rules="{ required: true, message: '请选择名称' }">
								<a-select v-model:value="editIndex[record.key].material.source_id" :show-search="true" placeholder="请选择名称" :options="materialNameOptions" option-filter-prop="label" allow-clear :disabled="editIndex[record.key].type !== 'add'" @change="changeMaterial(editIndex[record.key], 'material_name')"></a-select>
							</a-form-item>
						</template>
						<template v-else-if="column.dataIndex === 'model' && editIndex[record.key]">
							<a-form-item :name="[record.key, 'material', 'model']" :rules="{ required: true, message: '请选择物料规格' }">
								<a-select v-model:value="editIndex[record.key].material.model" :show-search="true" placeholder="请选择物料规格" :options="materialModelOptions[editIndex[record.key].material.source_id]" option-filter-prop="label" allow-clear :disabled="editIndex[record.key].type !== 'add'" @change="changeMaterial(editIndex[record.key], 'model')"></a-select>
							</a-form-item>
						</template>
						<!-- 计量单位 -->
						<template v-else-if="column.dataIndex === 'unit' && editIndex[record.key]">
							<a-form-item :name="[record.key, 'material', 'id']" :rules="{ required: true, message: '请选择计量单位' }">
								<a-select v-model:value="editIndex[record.key].material.id" :show-search="true" placeholder="请选择" :options="materialUnitOption[editIndex[record.key].material.source_id + '_' + editIndex[record.key].material.model]" allow-clear :disabled="editIndex[record.key].type !== 'add'" @change="changeMaterial(editIndex[record.key], 'unit')"></a-select>
							</a-form-item>
						</template>
						<!-- 品牌/厂家 -->
						<template v-else-if="column.dataIndex === 'brand_id' && editIndex[record.key]">
							<a-form-item :name="[record.key, 'brand_id']">
								<a-tree-select v-model:value="editIndex[record.key].brand_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择品牌/厂家" allow-clear tree-default-expand-all :tree-data="brandTree" tree-node-filter-prop="label" :check-strictly="true" :disabled="editIndex[record.key].type !== 'add'" style="width:100%" @change="changeMaterial(editIndex[record.key], 'brand_id')">
									<template #title="{ label, value }">{{ label }}
										<a-button size="small" @click.stop="addBrand(value)">+</a-button>
									</template>
								</a-tree-select>
							</a-form-item>
						</template>
						<!-- 区域 -->
						<template v-else-if="column.dataIndex === 'region' && editIndex[record.key]">
							<a-form-item :name="[record.key, 'region']" :rules="{ required: true, message: '区域' }">
								<a-cascader v-model:value="editIndex[record.key].region" :check-strictly="true" :options="regionOptions" :load-data="loadRegionData" placeholder="请选择区域" change-on-select :disabled="editIndex[record.key].type !== 'add'" @blur="changeMaterial(editIndex[record.key], 'region')" />
							</a-form-item>
						</template>
						<!-- 生效时间 -->
						<template v-else-if="column.dataIndex === 'effective_date_range' && editIndex[record.key]">
							<a-form-item :name="[record.key, 'effective_date_range']" :rules="{ required: true, message: '请选择生效时间' }">
								<a-range-picker v-model:value="editIndex[record.key].effective_date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate(editIndex[record.key])" :disabled="editIndex[record.key].is_exit" />
							</a-form-item>
						</template>
						<template v-else-if="column.dataIndex === 'price'">
							<a-form-item v-if="editIndex[record.key]" :name="[record.key, 'price']" :rules="{ required: true, message: '请输入不含税基准价' }">
								<a-input-number v-model:value="editIndex[record.key].price" style="width: 100%;" placeholder="请输入不含税基准价" min="0" :precision="2" allow-clear :disabled="editIndex[record.key].is_exit"></a-input-number>
							</a-form-item>
							<template v-else-if="record.price">
								{{ record.price }}
							</template>
							<template v-else>
								<span style="color: red;">暂无</span>
							</template>
						</template>
						<template v-else-if="column.dataIndex === 'file_path'">
							<a-form-item v-if="editIndex[record.key]" :name="[record.key, 'file_path']" :rules="{ required: true, message: '请上传文件' }">
								<a-upload v-model:file-list="editIndex[record.key].file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" size="middle" @change="fileUpload(record.key, $event)">
									<a-button>
										<template v-if="editIndex[record.key].upload">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传附件
										</template>
									</a-button>
								</a-upload>
							</a-form-item>
							<template v-else-if="record.file_path && record.file_path[0]">
								<a :href="record.file_path[0].url" target="_blank">{{ record.file_path[0].name }}</a>
							</template>
							<template v-else>
								<span>无</span>
							</template>
						</template>
						<template v-else-if="column.key === 'operation'">
							<a-space v-if="editIndex[record.key]">
								<a-button v-permission="264" type="link" :loading="editIndex[record.key].loading" @click="saveEditIndex(record.key, index)">
									保存
								</a-button>
								<a-popover v-if="editIndex[record.key].error" placement="top">
									<template #content>
										<span style="color:#ff7875">{{ editIndex[record.key].error }}</span>
									</template>
									<a-button style="color:#ff7875" type="link">
										失败原因
									</a-button>
								</a-popover>
								<a-button v-if="editIndex[record.key].type === 'add'" v-permission="264" style="color:#ff7875" type="link" :disabled="editIndex[record.key].loading" @click="cancelEditIndex(record.key, index)">
									<delete-outlined />删除
								</a-button>
								<a-button v-else v-permission="264" type="link" :disabled="editIndex[record.key].loading" @click="cancelEditIndex(record.key, index)">
									取消
								</a-button>
							</a-space>
							<a-space v-else>
								<a-button v-if="!editIndex[index]" v-permission="264" type="link" :disabled="(record.maintainer?.id && record.maintainer?.id !== userInfo?.id) || dayjs(record.setting_date).format('YYYY-MM-DD') > dayjs().format('YYYY-MM-DD')" @click="changeEditIndex(record)">
									<snippets-outlined />编辑
								</a-button>
								<a-button v-permission="264" type="link" @click="showPrice(record)">
									<snippets-outlined />查看历史价
								</a-button>
							</a-space>
						</template>
					</template>
				</a-table>
			</a-form>
		</div>
		<div>
			<div class="py-4 text-center">
				<a-space>
					<a-button v-if="toReturn" @click="closeTab('/price')">
						<close-outlined />关闭
					</a-button>
					<a-button v-if="!!Object.values(editIndex).filter(value => value).length" type="primary" :loading="saveListLoading" @click="saveList()">
						<save-outlined />保存
					</a-button>
				</a-space>
			</div>
		</div>
		<a-modal v-model:visible="visible" :width="400" title="添加数据" @ok="saveBrand">
			<a-form ref="formRef" :model="formState" style="margin-top: 20px;">
				<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
					<a-input v-model:value="formState.name" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>
<script setup>
import { computed, getCurrentInstance, inject, onMounted, reactive, ref } from "vue";
import { post, postJson } from "@/utils/index.js";
import { usePagination } from "vue-request";
import { useRoute, useRouter } from "vue-router";
import { cloneDeep } from 'lodash-es';
import { CloseOutlined, DeleteOutlined, EditOutlined, SnippetsOutlined } from "@ant-design/icons-vue";
import dayjs from "dayjs";
import { listToTree } from "../utils";
import { userStore } from "../store";
import { baseURL } from "@/utils/request.js";
const store = userStore();
const userInfo = store.info;
const searchState = reactive({
	status: 0,
	price_type: 1,
	setting_date: dayjs(),
});
const projectOptions = ref([]);
const companyOptions = ref([]);
const formModalRef = ref();
const formDataList = ref([]);
const loading = ref(false);
const saveListLoading = ref(false);
const editRef = ref();
const { proxy } = getCurrentInstance();
const priceTypeOptions = ref([
	{
		value: 1,
		label: "月浮动物资"
	},
	{
		value: 2,
		label: "日浮动物资"
	},
]);
const route = useRoute();
const router = useRouter();
const query = route.query;
const toReturn = query.toReturn;
const statusList = [
	{
		value: 0,
		label: "全部"
	},
	{
		value: 2,
		label: "待维护"
	},
	{
		value: 1,
		label: "已维护"
	}
];
const visible = ref(false);
const formState = ref({});
const formRef = ref();
// 添加品牌厂家
const addBrand = id => {
	formState.value = {
		parent_id: id
	};
	visible.value = true
}
// 保存品牌厂家
const saveBrand = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };

			post("dictionary/save", params)
				.then(data => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;
					// 保存成功后调品牌厂家下拉列表
					dictionaryList()
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};
// 禁用特定时间范围外的日期
const disabledDate = (record) => {
	return (current) => {
		// 禁用选择月份之前的日期
		if (dayjs(current).format('YYYY-MM') < dayjs(record.setting_date).format('YYYY-MM')) {
			return true;
		}
		return false;
	};
}
// 获取品牌下拉数据
const brandTree = ref([]);
onMounted(async () => {
	dictionaryList()
})
const dictionaryList = async () => {
	const dictionaryResult = await post("dictionary", { root_id: 1414 })
	const dataMap = {};
	for (const d of dictionaryResult) {
		dataMap[d.id] = d;
		if (dataMap[d.parent_id]) {
			dataMap[d.parent_id].disabled = true;
		}
	}
	brandTree.value = listToTree(dictionaryResult, 1414)
}
const materialOptions = ref([]);
const materialNameOptions = ref([]);
const materialModelOptions = ref({});
const materialUnitOption = ref({});
post("price/fd/materials").then((data) => {
	materialOptions.value = data;
	const map = {};
	const modelMap = {};
	const unitMap = {};
	for (const material of data) {
		map[material.source_id] = {
			value: material.source_id,
			label: material.name,
		};
		if (!modelMap[material.source_id]) {
			modelMap[material.source_id] = [{
				value: material.model,
				label: material.model,
			}]
		} else {
			modelMap[material.source_id].push({
				value: material.model,
				label: material.model,
			})
		}
		if (!unitMap[material.source_id + '_' + material.model]) {
			unitMap[material.source_id + '_' + material.model] = [{
				value: material.id,
				label: material.unit,
			}]
		} else {
			unitMap[material.source_id + '_' + material.model].push({
				value: material.id,
				label: material.unit,
			})
		}
	}
	for (const key in modelMap) {
		materialModelOptions.value[key] = modelMap[key];
	}
	for (const key in unitMap) {
		materialUnitOption.value[key] = unitMap[key];
	}
	materialNameOptions.value = Object.values(map);
});
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24])
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const getProjects = async () => {
	const projectResult = await post("price/fd/projects");
	projectOptions.value = projectResult.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(",").map(item => parseInt(item)),
			region: d.region,
		};
	});
}
getProjects()
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
});
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: "浮动物资类型",
		dataIndex: "priceMaterial",
		sorter: false,
		width: 100,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record?.price_type === 1 ? "月浮动物资" : "日浮动物资";
		}
	},
	{
		title: "物资名称",
		dataIndex: "name",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record.priceMaterial?.material?.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "model",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record.priceMaterial?.material?.model;
		}
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		sorter: false,
		width: 80,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record.priceMaterial?.material?.unit;
		}
	},
	{
		title: "品牌/厂家",
		dataIndex: "brand_id",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record.priceMaterial?.brand_text;
		}
	},
	{
		title: "区域",
		dataIndex: "region",
		key: "region",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record.priceMaterial?.region_text;
		}
	},
	{
		title: "设置年月",
		dataIndex: "setting_date",
		sorter: false,
		width: 120,
		ellipsis: true,
	},
	{
		title: "生效时间",
		dataIndex: "effective_date_range",
		sorter: false,
		width: 220,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			if (text) {
				return dayjs(text[0]).format('YYYY-MM-DD') + '~' + dayjs(text[1]).format('YYYY-MM-DD')
			} else {
				return '';
			}
		}
	},
	{
		title: "不含税基准价",
		dataIndex: "price",
		sorter: false,
		width: 100,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return record.price || '暂无';
		}
	},
	{
		title: "附件",
		dataIndex: "file_path",
		sorter: false,
		width: 150,
	},
	{
		title: "维护人",
		dataIndex: "user",
		sorter: false,
		width: 100,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.fullname;
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];
const innerColumns = ref(columns);
const editIndex = ref({});
const changeInnerColumns = () => {
	let _column = [...columns];
	const priceType = listQuery.value.price_type;
	const _priceType = parseInt(priceType);
	const settingDateColumn = _column.find(item => item.dataIndex === 'setting_date');
	settingDateColumn.title = _priceType === 1 ? '设置年月' : '设置日期';
	settingDateColumn.customRender = ({ text, record, index, column }) => {
		return _priceType === 1 ? dayjs(record.setting_date).format('YYYY-MM') : dayjs(record.setting_date).format('YYYY-MM-DD');
	}
	if (_priceType !== 1) {
		_column = _column.filter(item => item.dataIndex !== 'effective_date_range')
	}
	innerColumns.value = _column;
}
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const listQuery = ref({});
const initData = async () => {
	const filters = { ...searchState };
	if (searchState.setting_date) {
		filters.setting_date = dayjs(searchState.setting_date).format("YYYY-MM-DD");
	}
	const query = {};
	router.replace({ query: {
		...query,
		...filters
	}})
	listQuery.value = {
		...searchState,
		setting_date: searchState.setting_date ? dayjs(searchState.setting_date).format("YYYY-MM-DD") : null,
	}
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		listQuery.value.project_ids = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
	}
	changeInnerColumns()
	loading.value = true;
	try {
		const result = await post("price/fd", listQuery.value);
		formDataList.value = formatDates(result.data);
		loading.value = false;
	} catch (e) {
		loading.value = false;
		proxy.$message.error(e);
	}
};
if (query) {
	if (query.status) searchState.status = parseInt(query.status);
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.material_name) searchState.material_name = query.material_name;
	if (query.price_type) searchState.price_type = parseInt(query.price_type);
	if (query.setting_date) searchState.setting_date = dayjs(query.setting_date);
	if (query.toReturn) searchState.toReturn = query.toReturn;
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

// 格式化数据结构
const formatDates = (data = []) => {
	const _time = Date.now(),
		random = parseInt(Math.random() * 100);
	return data.map((d, index) => {
		if (d.children?.length === 0) delete d.children;
		d.setting_date = dayjs(d.setting_date)
		const { material, brand_id, region, price_type } = d.priceMaterial;
		d.material = material;
		d.key = _time + '' + index + random;
		Object.assign(d, {
			brand_id, region, price_type
		})
		return d;
	})
}

const addPrice = () => {
	const priceType = Number(listQuery.value.price_type);
	const record = {
		type: 'add',
		price_type: priceType,
		setting_date: priceType === 1 ? dayjs(listQuery.value.setting_date).format('YYYY-MM') : dayjs(listQuery.value.setting_date).format('YYYY-MM-DD'),
		material: {},
		region: [],
		key: Date.now() + '' + formDataList.value.length + parseInt(Math.random() * 100),
		file_path: [],
	}
	if (priceType === 1) {
		record['effective_date_range'] = [
			record.setting_date + '-01 23:59:59',
			dayjs(record.setting_date + '-01').endOf('month').format('YYYY-MM-DD 23:59:59'),
		];
	}
	formDataList.value.push(record);
	editIndex.value[record.key] = cloneDeep(record);
};

const regionCache = {};
const getRegion = async parentId => {
	if (regionCache[parentId]) return regionCache[parentId];
	regionCache[parentId] = await post("region/cascader", { parent_id: parentId });
	return regionCache[parentId];
};
const regionOptions = ref([]);
getRegion(0).then(data => {
	regionOptions.value = data;
});
const loadRegionData = options => {
	const option = options[options.length - 1];
	if (option.level === 1) {
		option.loading = true;
		return getRegion(option.value).then(data => {
			option.loading = false;
			option.children = data;
			regionOptions.value = [...regionOptions.value];
		});
	} else {
		option.loading = false;
		option.children = [];
		regionOptions.value = [...regionOptions.value];
	}

};
const changeEditIndex = async (record) => {
	editIndex.value[record.key] = cloneDeep(record);
	const region = editIndex.value[record.key].region;
	if (region && region.length) {
		try {
			if (region[1]) regionOptions.value.find(d => d.value === parseInt(region[0])).children = await getRegion(region[0]);
			if (region[2]) regionOptions.value.find(d => d.value === parseInt(region[0])).children.find(d => d.value === parseInt(region[1])).children = await getRegion(region[1]);
		} catch (err) {
			//proxy.$message.error(err);
		}
	}
	editIndex.value[record.key].file_path = [];
	// if (editIndex.value[record.key].file_path) {
	// 	editIndex.value[record.key].file_path = JSON.parse(editIndex.value[record.key].file_path)
	// } else {
	// 	editIndex.value[record.key].file_path = [];
	// }
}

// 改变物料时触发
const changeMaterial = async (record, column) => {
	switch (column) {
	case 'material_name':
		record.material.model = null;
		record.material.id = null;
		break;
	case 'model':
		record.material.id = null;
		break;
	}
	const [material_id, brand_id = 0, price_type, region, setting_date] = [
		record.material.id, record.brand_id, record.price_type, record.region,
		record.price_type === 1 ? dayjs(record.setting_date + '-01').format('YYYY-MM-DD') : dayjs(record.setting_date).format('YYYY-MM-DD'),
	]
	if (!material_id || !price_type || !region || !region.length || !setting_date) {
		return;
	}
	const result = await postJson("price/fd/manage/price", {
		material_id, brand_id, price_type, region, setting_date,
	})
	if (result.priceManage) {
		record.is_exit = true;
		record.price = result.priceManage.price;
		record.effective_date_range = result.priceManage.effective_date_range;
	} else {
		record.is_exit = false;
	}
}
const fileUpload = (key, { file }) => {
	const record = editIndex.value[key];
	if (file.status === "done") {
		record.file_path = [{
			name: file.name,
			url: file.response.data.url
		}];
		record.upload = false;
		proxy.$message.success("附件上传成功");
	}
	if (!file.status) {
		record.file_path = record.file_path.filter((item) => item.url)
	}
};
const saveEditIndex = async (key, index) => {
	const record = editIndex.value[key];
	record.error = null;
	const validateFields = [
		[key, 'material', 'source_id'],
		[key, 'material', 'model'],
		[key, 'material', 'id'],
		[key, 'region'],
		[key, 'effective_date_range'],
		[key, 'price'],
		[key, 'file_path']
	]
	try {
		await editRef.value.validateFields(validateFields);
		// console.log('校验通过')
	} catch (e) {
		// console.log('校验不通过')
		record.loading = false;
		return;
	}
	const params = {
		id: record.id,
		price: record.price,
		material_id: record.material.id,
		region: record.region,
		price_type: record.price_type,
		brand_id: record.brand_id || 0,
		effective_date_range: record.effective_date_range,
		file_path: record.file_path,
	}
	if (record.price_type === 1) {
		params.setting_date = dayjs(record.setting_date).format('YYYY-MM-01')
	} else {
		params.setting_date = dayjs(record.setting_date).format('YYYY-MM-DD')
	}
	params.material_type = materialOptions.value.find(item => item.id === params.material_id)?.material_type;
	record.loading = true;
	try {
		const result = await postJson("price/fd/save", params);
		record.loading = false;
		// proxy.$message.success("提交成功", 1);
		formDataList.value[index] = formatDates([result])[0];
		editIndex.value[key] = null;
	} catch (e) {
		record.error = e.message || e;
		record.loading = false;
	}
}

const cancelEditIndex = (key, index) => {
	if (editIndex.value[key].type === 'add') {
		formDataList.value.splice(index, 1);
	}
	editIndex.value[key] = null;
}

// 批量保存
const saveList = async () => {
	saveListLoading.value = true;
	for (const key in editIndex.value) {
		if (editIndex.value[key]) {
			editIndex.value[key].loading = true;
		}
	}
	for (let i = 0; i < formDataList.value.length; i++) {
		const record = formDataList.value[i];
		if (editIndex.value[record.key]) {
			await saveEditIndex(record.key, i);
		}
	}
	saveListLoading.value = false;
	proxy.$message.success("操作完毕", 1);
}
const showPrice = record => {
	router.push(`/pricefd/history?material_id=${record.priceMaterial?.material_id}&price_type=${record.priceMaterial.price_type}&region=${JSON.stringify(record.priceMaterial.region)}&brand_id=${JSON.stringify(record.priceMaterial.brand_id)}`);
}
const closeTab = inject("closeTab");
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
  .table{
	:deep(.ant-table-cell) .ant-form-item {
		margin-bottom: 0;
		.ant-form-item-explain {
			position: absolute;
			bottom: -24px;
		}
	}	
	:deep .ant-select-selection-item{
		// background: red;
		.ant-btn{
			display: none;
		}
	}
  }
}
</style>